<template>
  <Card dis-hover :bordered="false">
    <Form inline>
      <Button
        type="primary"
        @click="handleAdd"
        class="ivu-mb-16"
        v-hasC="{
          name: 'v1-department-create',
          flag: 'v1/department/create',
        }"
        >新增</Button
      >
    </Form>
    <Table
      :columns="columns"
      :data="list"
      :loading="loading"
      @on-sort-change="sortChange"
      :max-height="tableHeigth"
    >
      <template #status_str="{ row }">
        <Badge
          status="success"
          :text="row.status_str"
          v-if="row.status_str === '启用'"
        />
        <Badge status="error" :text="row.status_str" v-else />
      </template>

      <template #action="{ row }">
        <a
          @click="handleEdit(row)"
          v-hasC="{
            name: 'v1-department-update',
            flag: 'v1/department/update',
          }"
          >编辑</a
        >
        <Divider
          type="vertical"
          v-hasC="{
            name: 'v1-department-update',
            flag: 'v1/department/update',
          }"
        />
        <a
          @click="handleDel(row.id)"
          class="del"
          v-hasC="{
            name: 'v1-department-delete',
            flag: 'v1/department/delete',
          }"
          >删除</a
        >
      </template>
    </Table>
    <Page
      class="ivu-mt-16"
      :total="total"
      :modelValue="params.current"
      :page-size="params.size"
      :page-size-opts="pageOpts"
      show-total
      show-sizer
      @on-change="changePage"
      @on-page-size-change="changepageSize"
    />
    <Modal
      :mask-closable="false"
      v-model="addModal"
      :title="edit ? '新增' : '编辑'"
      :footer-hide="true"
      :draggable="true"
    >
      <Form
        ref="create"
        :model="departmentInfo"
        :rules="rules"
        :label-width="60"
      >
        <FormItem label="名称" prop="department_name" required>
          <Input
            v-model="departmentInfo.department_name"
            placeholder="请输入名称"
            :maxlength="30"
          />
        </FormItem>

        <FormItem label="排序" prop="sort">
          <InputNumber
            v-model="departmentInfo.sort"
            placeholder="排序"
            :min="0"
          />
        </FormItem>
        <FormItem label="状态" prop="status">
          <Switch v-model="departmentInfo.status" />
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: right">
        <Button type="default" @click="addModal = false">取消</Button>
        <Button
          type="primary"
          @click="ok"
          style="margin-left: 10px"
          :loading="btnLoading"
          >确定</Button
        >
      </div>
    </Modal>
  </Card>
</template>
<script>
import {
  departmentList,
  createDepartment,
  deleteDepartment,
  departmentInfo,
  updateDepartment,
} from "@api/department.js";
export default {
  name: "department",
  data() {
    return {
      tableHeigth: document.body.clientHeight - 270,
      addModal: false,
      edit: true,
      loading: false,
      btnLoading: false,
      params: {
        current: 1,
        size: 10,
        status: "",
        order_column: "",
        order_sort: "",
      },
      total: 0,
      pageOpts: [10, 20, 30, 40],
      columns: [
        {
          key: "id",
          title: "ID",
          width: 80,
        },
        {
          key: "department_name",
          title: "部门",
          minWidth: 125,
        },
        {
          key: "member_num",
          title: "部门人数",
          sortable: "custom",
        },
        {
          key: "sort",
          title: "排序",
        },
        {
          slot: "status_str",
          title: "状态",
          width: 118,
        },
        {
          slot: "action",
          title: "操作",
          width: 110,
          fixed: "right",
        },
      ],
      list: [],
      departmentInfo: {
        id: "",
        department_name: "",
        sort: 100,
        status: true,
      },
      rules: {
        department_name: [{ required: true, message: "请输入部门名称" }],
      },
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    //切换page
    changePage(index) {
      this.params.current = index;
      this.getData();
    },
    changepageSize(val) {
      this.params.size = val;
      this.getData();
    },
    handleDel(index) {
      this.$Modal.confirm({
        title: "删除提示",
        content: "是否确认删除此条记录，删除后不可恢复",
        onOk: () => {
          deleteDepartment({ id: index })
            .then(() => {
              this.$Message.success("删除成功");
              this.getData();
            })
            .catch(() => {});
        },
      });
    },
    handleAdd() {
      this.departmentInfo = {
        id: "",
        department_name: "",
        sort: 100,
        status: true,
      };
      this.addModal = true;
      this.edit = true;
      this.$refs.create.resetFields();
    },
    handleEdit(info) {
      this.addModal = true;
      this.edit = false;
      departmentInfo({ id: info.id })
        .then((res) => {
          this.departmentInfo = {
            id: res.id,
            department_name: res.department_name,
            sort: res.sort,
            status: res.status == 1 ? true : false,
          };
        })
        .catch(() => {});
    },
    sortChange(e) {
      this.params.order_column = e.key.replace(/_str$/, "");
      this.params.order_sort = e.order;
      this.getData();
    },
    getData() {
      this.loading = true;
      const params = {
        pageSize: this.params.size,
        page: this.params.current,
        status: this.params.status,
        order_column: this.params.order_column,
        order_sort: this.params.order_sort,
      };
      departmentList(params)
        .then((res) => {
          this.list = res.list;
          this.total = res.total;
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    addDepartment() {
      this.btnLoading = true;
      const params = {
        department_name: this.departmentInfo.department_name,
        sort: this.departmentInfo.sort,
        status: this.departmentInfo.status ? 1 : 0,
      };
      if (this.edit) {
        createDepartment(params)
          .then((res) => {
            this.$Message.success("添加成功");
            this.addModal = false;
            this.btnLoading = false;
            this.params.current = 1;
            this.getData();
          })
          .catch(() => {
            this.btnLoading = false;
          });
      } else {
        updateDepartment(
          Object.assign({}, params, { id: this.departmentInfo.id })
        )
          .then((res) => {
            this.$Message.success("编辑成功");
            this.addModal = false;
            this.btnLoading = false;
            this.getData();
          })
          .catch(() => {
            this.btnLoading = false;
          });
      }
    },
    ok() {
      this.$refs.create.validate((valid) => {
        if (valid) {
          this.addDepartment();
        } else {
          this.addModal = true;
          this.$Message.error("填写错误，保存失败！");
          return;
        }
      });
    },
  },
};
</script>